﻿/*
   Author: Tomer Paz
   games.com
   2007
*/
// game board Collection implementation

package monopoly.GameBoard {
	
// boards container class. implements ICollection. manages boards and fields. A Singleton. also implement event dispatching,
// since it has to broadcast any one who's listenning - once a new board is active ("Current" active board ID)

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import monopoly.IFS.Collections.ICollection;
	import monopoly.IFS.iterators.ArrayIterator;
	import monopoly.IFS.iterators.IIterator;

	public class GameBoardCollection extends EventDispatcher implements ICollection
		{
		private var _Boards:Array;
		private var _ActiveBoardIndex:uint;
	
		// for Singelton implementation:
		private static var _instance:GameBoardCollection;
	
		public function GameBoardCollection(parameter:SingletonEnforcer)
			{
			}

		public static function getInstance():GameBoardCollection 
			{
	        if(_instance == null) 
				{
	            _instance = new GameBoardCollection(new SingletonEnforcer());
				_instance._Boards = new Array();
				_instance._ActiveBoardIndex = 0;	// Default active board is the first one
	         	}
	        return GameBoardCollection._instance;
	      	}

		
		public function addBoard(value:GameBoard):void
			{
			_instance._Boards.push(value);
			}
			
		// set Active (current) board - checks for correct input and return false if incorrect (out of bounds)
		public function SetActiveBoard(ActiveBoardIndex:uint):Boolean
			{
			if ( ActiveBoardIndex < 0 || ActiveBoardIndex > (_instance._Boards.length - 1) )
				return false;
				
			_instance._ActiveBoardIndex = ActiveBoardIndex;
			
			//whoever listens, please update yourself (probably GameBoardCollection View! or GameController)
			try 
				{
				dispatchEvent(new Event(Event.CHANGE));
				}
			catch(e:Error)
				{
				trace("The event dispatch recursion limit has been reached");
				return false;
				}
			
			return true;
			}
		// return the Current active Board 	
		public function get ActiveBoard():GameBoard
			{
			return _instance._Boards[_instance._ActiveBoardIndex];
			}
		public function get ActiveBoardIndex():uint
			{
			return _instance._ActiveBoardIndex;
			}
		
		public function iterator(type:String = null):IIterator 
			{
		    return new ArrayIterator(_instance._Boards);
			}
		
		//not part of ICollection interface:
		public function get length():uint
			{
			return _instance._Boards.length;
			}
		}
}
class SingletonEnforcer { }